package sample.server;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sample.shared.Consts;
import sample.shared.FileExtensions;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

@SuppressWarnings("serial")
@Singleton
public class EditServlet extends HttpServlet
{
  private String clientRootDir;

  @Inject
  public EditServlet(@Named("dir.clientroot") String clientRootDir) {
    this.clientRootDir = clientRootDir;
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response) {
    String clientCode = request.getParameter("clientCode");
    String docPath = request.getParameter("docPath");
    String docName = request.getParameter("docName");

    if (FileExtensions.getType(docName.substring(1 + docName.lastIndexOf(".")))
        .equals(FileExtensions.OTHER)) return;

    String s =
        "\""
            + ClientManagerServiceImpl.getFileFromCode(clientRootDir,
                clientCode) + File.separator + docPath + File.separator
            + docName + "\"" + Consts.NEWLINE + "del action*.*"
            + Consts.NEWLINE;
    try {
      sendBinaryFile(response, s.getBytes(), "action.cm");
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  void sendBinaryFile(HttpServletResponse response, byte[] bytes, String name)
      throws IOException
  {
    ServletOutputStream stream = null;

    response.setContentType("application/octet-stream");
    response.setContentLength(bytes.length);
    response.setHeader("Content-Transfer-Encoding", "binary");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + name
        + "\"");

    stream = response.getOutputStream();
    stream.write(bytes);
    stream.close();
  }
}
